﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Configuration;
using System.Xml;
namespace A41Backup
{
    public partial class frmChooseDB : Form
    {
        DataTable dtServers = SmoApplication.EnumAvailableSqlServers(true);
        private static Server srvr;
        private string DBpath = Application.StartupPath;

        public frmChooseDB()
        {
            InitializeComponent();
        }

        private void Backup_Load(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
            WindowState = FormWindowState.Normal;
            try
            {
                // If there are any servers
                if (dtServers.Rows.Count > 0)
                {
                    // Loop through each server in the DataTable
                    foreach (DataRow drServer in dtServers.Rows)
                    {
                        cmbServer.Items.Add(drServer["Name"]);
                        cmbServer.Text = Convert.ToString(drServer["Name"]);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("ERROR: There are no available servers.\nOr there is an error while loading server name", "Server Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                this.Cursor = Cursors.Default;
            }
            this.Cursor = Cursors.Default;
        }   
       

        private void cmbDataBase_Click(object sender, EventArgs e)
        {
            cmbDataBase.Items.Clear();
            try
            {
                if (cmbServer.SelectedItem != null && cmbServer.SelectedItem.ToString() != "")
                {
                    this.Cursor = Cursors.WaitCursor;
                    // Create a new connection to the selected server name
                    ServerConnection srvConn = new ServerConnection(cmbServer.SelectedItem.ToString());
                    // Log in using SQL authentication instead of Windows authentication
                    srvConn.LoginSecure = true;
                    // Create a new SQL Server object using the connection we created
                    srvr = new Server(srvConn);
                    // Loop through the databases list
                    foreach (Database dbServer in srvr.Databases)
                    {
                        // Add database to combobox
                        cmbDataBase.Items.Add(dbServer.Name);
                    }                    
                }
                else
                {
                    // A server was not selected, show an error message
                    MessageBox.Show("ERROR: Contact Administrator!!", "Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("ERROR: An error ocurred while loading the avaiable DataBasees", "Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void db_change_Click(object sender, EventArgs e)
        {
            cmbDataBase.Enabled = true;
        }

        private void cmbServer_SelectedValueChanged(object sender, EventArgs e)
        {
            //cmbServer.Enabled = false;
        }

        private void cmbDataBase_SelectedValueChanged(object sender, EventArgs e)
        {
            //cmbDataBase.Enabled = false;
        }

        private void btn_backup_Click(object sender, EventArgs e)
        {
            string connectString = "";
            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

                string server = cmbServer.Text;
                string db = cmbDataBase.Text ;
                string user = txt_username.Text ;
                string pass = txt_password.Text ;
                connectString = String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", server, db, user, pass);

                xmlDoc.SelectSingleNode("//connectionStrings/add").Attributes["connectionString"].Value = connectString;
                xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

                ConfigurationManager.RefreshSection("connectionStrings");

                //System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);

                ////Read the value
                //MessageBox.Show(config.AppSettings.Settings["ConnectionString"].Value);

                ////Write a new value
                //config.AppSettings.Settings.Remove("ConnectionString");
                //config.AppSettings.Settings.Add("ConnectionString", "Your New Connection String");

                ////Save the configuration file.
                //config.Save(System.Configuration.ConfigurationSaveMode.Modified);
                //System.Configuration.ConfigurationManager.RefreshSection("appSettings");             
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //hiển thị lại config
            MessageBox.Show(global::A41Backup.Properties.Settings.Default.QLVT_A41ConnectionString, "Thành công");
        }
    }
}
